package com.appspot.mscheckers;

import java.util.Date;

import com.appspot.mscheckers.core.CheckerModel;
import com.appspot.mscheckers.core.MoveTable;
import com.appspot.mscheckers.core.Position;

public class Game {
	private String userId1;
	private String userId2;
	private Date date;
	private char turn;
	private char[][] cBoard;
	private Position[][] mt = null;
	private int mtIndex;
	
	public Game(String userId1, String userId2){
		this.userId1 = userId1;
		this.userId2 = userId2;
		//this.nGame = 0;
		date = new Date();
		turn = 'w';
		cBoard = CheckerModel.checkerBoard();
		mtIndex = 0;
	}

	public boolean move(Position[] mtr, char piece){
		
		Checkers.log.info(viewMTR(mtr));
		
		if( !isValidMove(mtr) ) 
			return false;
	
		Position p,q, pb;
		for(int i = 0; i < mtr.length-1; i++){
			p = mtr[i];
			q = mtr[i+1];
			Checkers.log.info("Iteration : "+i+"move from "+p.getY()+","+p.getX()+" to "+q.getY()+","+q.getX());
			Checkers.log.info(viewCBoard());
			Checkers.log.info(cBoard[q.getY()][q.getX()]+"");
			Checkers.log.info(cBoard[p.getY()][p.getX()]+"");
			cBoard[q.getY()][q.getX()] = cBoard[p.getY()][p.getX()];
			cBoard[p.getY()][p.getX()] = 'v';
			if( (pb= Position.pawnBetween(p, q, cBoard) ) != null )
			{
				cBoard[pb.getY()][pb.getX()] = 'v';
			}
			mtIndex++;
		}
		
		if( mtIndex == mt[0].length - 1 ){
			mtIndex = 0;
			mt = null;
		}
		return true;
	}
	
	private boolean isValidMove(Position[] mtr){
		//TO complete
		return true;
	}
	
	private String viewCBoard(){
		String r="\n";
		if(cBoard != null ){
			for(int j = 0; j < cBoard.length; j++){
				for(int i = 0; i < cBoard.length; i++){
					r += cBoard[j][i]+" ";
				}
			r+="\n";
			}
		}
		return r;
	}
	
	private String viewMTR(Position[] mtr){
		String r="\n";
			for(Position p : mtr){
				r+=p.getY()+" , "+p.getX()+"\n";
			}
		return r;
	}
	
	public Position[][] getMTable(char piece){
		///Test if piece == turn
		mt = MoveTable.moveTable(cBoard, piece);
		return mt;
	}

	public Position[][] getMTable(){
		return mt;
	}
	
	public char[][] getCBoard(){
		return cBoard;
	}
	
	public void setTurn(char turn){
		this.turn = turn;
	}
	
	public char getTurn(){
		return turn;
	}

	public char getRTurn(){
		return (turn=='w')?'b':'w';
	}

	public String getUserId(String userId) {
		return (userId1.equals(userId))?userId2:userId1;
	}
	
	public String getUserId1() {
		return userId1;
	}

	public String getUserId2() {
		return userId2;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
}
